class WebSocketService {
    private socket: WebSocket | null = null;
    private url: string;
    private heartbeatTimer: any;
    private heartbeatInterval: number;
    private reconnectAttempts: number;
    private maxReconnectAttempts: number;
    private reconnectInterval: number;

    constructor(url: string) {
        this.url = url;
        this.heartbeatTimer = null;
        this.heartbeatInterval = 30000; // 30秒
        this.reconnectAttempts = 0;
        this.maxReconnectAttempts = 5;
        this.reconnectInterval = 5000; // 5秒
    }

    startHeartbeat() {
        this.heartbeatTimer = setInterval(() => {
            this.send({ type: 'heartbeat' });
        }, this.heartbeatInterval);
    }

    stopHeartbeat() {
        if (this.heartbeatTimer) {
            clearInterval(this.heartbeatTimer);
            this.heartbeatTimer = null;
        }
    }


    connect() {
        this.socket = new WebSocket(this.url);
        this.socket.onopen = this.onOpen.bind(this);
        this.socket.onmessage = this.onMessage.bind(this);
        this.socket.onclose = this.onClose.bind(this);
        this.socket.onerror = this.onError.bind(this);

        this.startHeartbeat();
    }

    reconnect() {
        if (this.reconnectAttempts < this.maxReconnectAttempts) {
            this.reconnectAttempts++;
            console.log(`尝试重新连接... (${this.reconnectAttempts}/${this.maxReconnectAttempts})`);
            setTimeout(() => {
                this.connect();
            }, this.reconnectInterval);
        } else {
            console.error('达到最大重连次数，连接失败');
        }
    }

    onOpen() {
        console.log('WebSocket连接已建立');
        this.reconnectAttempts = 0;
        this.startHeartbeat();
    }

    onMessage(event: MessageEvent) {
        console.log('收到消息:', event.data);
    }

    onClose() {
        console.log('WebSocket连接已关闭');
        this.stopHeartbeat();
        this.reconnect();
    }

    onError(error: Event) {
        console.error('WebSocket错误:', error);
    }

    send(data: any) {
        if (this.socket && this.socket.readyState === WebSocket.OPEN) {
            this.socket.send(JSON.stringify(data));
        } else {
            console.error('WebSocket未连接');
        }
    }

    close() {
        if (this.socket) {
            this.socket.close();
        }
    }
}

export default WebSocketService;
